import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import { DownOutlined } from '@ant-design/icons';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Button,
  Card,
  Row,
  Col,
  Input,
  Select,
  Table,
  Badge,
  Divider,
  Modal,
  Timeline,
  Tooltip,
  Menu,
  Dropdown,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

import { TableListItem, TableListData } from './data';

import SaveAndUpdateElem from './components/SaveAndUpdateElem';

const { Option } = Select;
const { Item } = Form;
const statusTag: any = ['error', 'success'];
const statusText = ['无效', '有效'];
const typeText = ['校园', '小区'];

const { pathname } = window.location;

interface PartitionInfoProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  dataInfo: TableListData;
  INITINFO: any;
  location: { query?: any };
  screen: string;
}

interface PartitionInfoState {
  searchValues: any;
  type: string;
  detail: TableListItem | any;
  visible: boolean;
  statusInfo: {
    id: number | string;
    status: number;
  };
  statusVisible: boolean;
  logVisible: boolean;
  update: {
    updateUserName: string;
    updateTime: string;
    createUserName: string;
    createTime: string;
  };
  pageIndex:number;
  pageSize:number;
  rowId:number;
}

@connect(
  ({
    partitionManagement: { dataInfo },
    common: { INITINFO },
    loading,
    global: { screen },
  }: any) => ({
    dataInfo,
    INITINFO,
    loading: loading.effects['partitionManagement/fetch'],
    screen,
  }),
)
class PartitionInfoElem extends React.Component<PartitionInfoProps, PartitionInfoState> {
  columns = [
    {
      title: '场景类型',
      dataIndex: 'type',
      width: 88,
      render: (val: number) => typeText[val - 1],
    },
    {
      title: '物流中心/小区',
      dataIndex: 'logisName',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '分区',
      dataIndex: 'name',
      width: 120,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            onClick={() => this.handleShowPartition(record.id, record.name)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render: (val: number) => <Badge status={statusTag[val]} text={statusText[val]} />,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 160,
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      width: 100,
    },
    {
      title: '操作',
      width: 120,
      render: (val: any, record: TableListItem) => (
        <>
          <span
            className="operLink"
            onClick={() => this.handleShowModal(true, record)}
          >
            编辑
          </span>
          <Divider type="vertical" />
          <span
            className="operLink"
            onClick={() => this.handleShowPartition(record.id, record.name)}
          >
            详情
          </span>
          <Divider type="vertical" />
          <Dropdown arrow overlay={() => this.menu(record)}>
            <span className="operLink">
              更多 <DownOutlined />
            </span>
          </Dropdown>
        </>
      ),
    },
  ];

  state: PartitionInfoState = {
    rowId: 0,
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    type: '1',
    detail: {},
    visible: false,
    statusInfo: {
      id: '',
      status: 0,
    },
    statusVisible: false,
    logVisible: false,
    update: {
      updateUserName: '',
      updateTime: '',
      createUserName: '',
      createTime: '',
    },
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...values } = query;
    return {
      searchValues: {
        ...values,
        type: values.type || '1',
      },
      type: values.type || '1',
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchAction('common/fetchLogisList');
    this.fetchAction('common/fetchGardenList');

    const { dataInfo } = this.props;
    if (dataInfo?.list?.length) return;

    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    const {
      form: { setFieldsValue },
    } = this.props;
    setFieldsValue(searchValues);
  };

  turnValuesType = (values: any) => {
    const params = {
      ...values,
      logisId: values.logisId && Number(values.logisId),
      gardenId: values.gardenId && Number(values.gardenId),
    };
    if (values.type === 1) delete params.gardenId;
    if (values.type === 2) delete params.logisId;
    return params;
  };

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  };

  menu = (record: any) => (
    <Menu>
      <Menu.Item className="operLink" onClick={() => this.handleChangeModal(true, record)}>
        设置无效
      </Menu.Item>
      <Menu.Item
        className="operLink"
        onClick={() => this.handleCabinetManager(record.id, record.name)}
      >
        柜体管理
      </Menu.Item>
      <Menu.Item className="operLink" onClick={() => this.handleLogModal(true, record)}>
        日志
      </Menu.Item>
    </Menu>
  );

  handleChangeModal = (statusVisible: boolean, record?: any) => {
    this.setState({
      statusVisible,
      statusInfo: {
        id: record ? record.id : '',
        status: 0,
      },
    });
  };

  handleSetInvalid = () => {
    const { searchValues: search, statusInfo } = this.state;
    const params = {
      search,
      ...statusInfo,
    };
    this.fetchAction('change', params);
    this.handleChangeModal(false);
  };

  handleShowModal = (status: boolean, record?: TableListItem) => {
    this.setState({
      detail: record || {},
      visible: status,
    });
  };

  /**
   * 查看分区
   */
  handleShowPartition = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${name}`,
      url: `/basic/partitionManagement/list/detail?id=${id}`,
    });
  };

  /**
   * 柜体管理
   */
  handleCabinetManager = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `柜体${name}`,
      url: `/basic/partitionManagement/list/cabinet?id=${id}`,
    });
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const query = {
        ...values,
        pageIndex: 1,
        pageSize: 20,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '分区管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '分区管理',
      url: pathname,
      isTopMenu: true,
    });
  };

  handleLogModal = (logVisible: boolean, record?: any) => {
    this.setState({
      logVisible,
      update: {
        updateUserName: record ? record.updateUserName : '',
        updateTime: record ? record.updateTime : '',
        createUserName: record ? record.createUserName : '',
        createTime: record ? record.createTime : '',
      },
    });
  };

  handleChangeType = (type: string) => this.setState({ type });

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '分区管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    if (typeName === 'saveAndUpdate') {
      const { searchValues: search } = this.state;
      payload = { search, ...payload };
    }

    const type = typeName.indexOf('common') >= 0
      ? typeName : `partitionManagement/${typeName}`;
    const { dispatch } = this.props;
    dispatch({
      type,
      payload,
    });
  };

  render() {
    const {
      type,
      pageIndex,
      pageSize,
      detail,
      visible,
      statusVisible,
      logVisible,
      update,
    } = this.state;

    const {
      form: { getFieldDecorator },
      dataInfo,
      INITINFO: { logisList, gardenList },
      loading,
    } = this.props;

    const dataSource = dataInfo.list || [];
    const pagination: object = dataInfo
      ? {
        total: dataInfo.count,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${dataInfo.count || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form
            hideRequiredMark
            className="tableListForm"
            onSubmit={this.handleSearch}
          >
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="　　场景类型" colon={false}>
                  {getFieldDecorator('type')(
                    <Select placeholder="请选择" onChange={this.handleChangeType}>
                      <Option value="1">校园</Option>
                      <Option value="2">小区</Option>
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="物流中心/小区" colon={false}>
                  {type === '1'
                    ? getFieldDecorator('logisId')(
                      <Select
                        showSearch
                        allowClear
                        placeholder="请选择"
                        filterOption={(input: any, option: any) => option.props.children
                          .toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                      >
                        {logisList.map((item: any) => (
                          <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                        ))}
                      </Select>,
                    )
                    : getFieldDecorator('gardenId')(
                      <Select
                        showSearch
                        allowClear
                        placeholder="请选择"
                        filterOption={(input: any, option: any) => option.props.children
                          .toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                      >
                        {gardenList.map((item: any) => (
                          <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                        ))}
                      </Select>,
                    )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　　　　分区" colon={false}>
                  {getFieldDecorator('name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={() => this.handleShowModal(true)}
            >
              新建分区
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 980 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <SaveAndUpdateElem
          detail={detail}
          visible={visible}
          fetchAction={this.fetchAction}
          logsList={logisList}
          gardenList={gardenList}
          showModal={this.handleShowModal.bind(this)}
        />

        <Modal
          title="确认提示"
          visible={statusVisible}
          onOk={this.handleSetInvalid}
          onCancel={() => this.handleChangeModal(false)}
        >
          <p>确定设置当前分区无效吗？</p>
        </Modal>

        <Modal
          title="日志信息"
          visible={logVisible}
          destroyOnClose
          footer={null}
          style={{ textAlign: 'left' }}
          onCancel={() => this.handleLogModal(false)}
        >
          <Timeline>
            <Timeline.Item>最近操作人：{update.updateUserName}</Timeline.Item>
            <Timeline.Item>最近操作时间：{update.updateTime}</Timeline.Item>
            <Timeline.Item>创建人：{update.createUserName}</Timeline.Item>
            <Timeline.Item>创建时间：{update.createTime}</Timeline.Item>
          </Timeline>
        </Modal>
      </>
    );
  }
}

export default Form.create<PartitionInfoProps>()(PartitionInfoElem);
